<template>
  <div class="main">
    <!-- 搜索表单 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" :inline="true" label-width="80px">
        <el-form-item label="用户名">
          <el-input
            v-model="filterForm.username"
            placeholder="请输入用户名"
            clearable
            class="!w-[150px]"
          />
        </el-form-item>
        <el-form-item label="登录状态">
          <el-select
            v-model="filterForm.status"
            placeholder="请选择状态"
            clearable
            class="!w-[120px]"
          >
            <el-option label="成功" value="success" />
            <el-option label="失败" value="failed" />
          </el-select>
        </el-form-item>
        <el-form-item label="登录方式">
          <el-select
            v-model="filterForm.loginType"
            placeholder="请选择登录方式"
            clearable
            class="!w-[140px]"
          >
            <el-option label="账号密码" value="password" />
            <el-option label="手机验证码" value="sms" />
            <el-option label="微信登录" value="wechat" />
            <el-option label="QQ登录" value="qq" />
          </el-select>
        </el-form-item>
        <el-form-item label="IP地址">
          <el-input
            v-model="filterForm.ip"
            placeholder="请输入IP地址"
            clearable
            class="!w-[150px]"
          />
        </el-form-item>
        <el-form-item label="登录时间">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            class="!w-[350px]"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <IconifyIconOffline :icon="Search" />
            查询
          </el-button>
          <el-button @click="handleReset">
            <IconifyIconOffline :icon="Refresh" />
            重置
          </el-button>
          <el-button type="success" @click="handleExport">
            <IconifyIconOffline :icon="Download" />
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="16" class="mb-4">
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon total-icon">
              <IconifyIconOffline :icon="User" />
            </div>
            <div class="stat-info">
              <div class="stat-title">总登录次数</div>
              <div class="stat-value">{{ loginStats.total }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon today-icon">
              <IconifyIconOffline :icon="Calendar" />
            </div>
            <div class="stat-info">
              <div class="stat-title">今日登录</div>
              <div class="stat-value">{{ loginStats.today }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon success-icon">
              <IconifyIconOffline :icon="Check" />
            </div>
            <div class="stat-info">
              <div class="stat-title">成功登录</div>
              <div class="stat-value">{{ loginStats.success }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon failed-icon">
              <IconifyIconOffline :icon="Close" />
            </div>
            <div class="stat-info">
              <div class="stat-title">失败登录</div>
              <div class="stat-value">{{ loginStats.failed }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 登录日志列表 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>登录日志列表</span>
          <div>
            <el-button type="info" @click="handleRefresh">
              <IconifyIconOffline :icon="Refresh" />
              刷新
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="loginList" style="width: 100%" stripe v-loading="loading">
        <el-table-column prop="id" label="日志ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="realName" label="用户姓名" width="100" />
        <el-table-column prop="loginType" label="登录方式" width="120">
          <template #default="{ row }">
            <el-tag size="small" :type="getLoginTypeTagType(row.loginType)">
              {{ getLoginTypeText(row.loginType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="登录状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 'success' ? 'success' : 'danger'" size="small">
              {{ row.status === 'success' ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ip" label="IP地址" width="130" />
        <el-table-column prop="location" label="登录地点" width="150" show-overflow-tooltip />
        <el-table-column prop="userAgent" label="设备信息" width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tooltip :content="row.userAgent" placement="top">
              <span>{{ getDeviceInfo(row.userAgent) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="loginTime" label="登录时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.loginTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="logoutTime" label="退出时间" width="160">
          <template #default="{ row }">
            {{ row.logoutTime ? formatDateTime(row.logoutTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="在线时长" width="120" align="center">
          <template #default="{ row }">
            {{ row.duration ? formatDuration(row.duration) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleView(row)">
              <IconifyIconOffline :icon="View" />
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 登录详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="登录日志详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="currentLogin" class="login-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="日志ID">{{ currentLogin.id }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{ currentLogin.username }}</el-descriptions-item>
          <el-descriptions-item label="用户姓名">{{ currentLogin.realName }}</el-descriptions-item>
          <el-descriptions-item label="登录方式">
            <el-tag size="small" :type="getLoginTypeTagType(currentLogin.loginType)">
              {{ getLoginTypeText(currentLogin.loginType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="登录状态">
            <el-tag :type="currentLogin.status === 'success' ? 'success' : 'danger'" size="small">
              {{ currentLogin.status === 'success' ? '成功' : '失败' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="IP地址">{{ currentLogin.ip }}</el-descriptions-item>
          <el-descriptions-item label="登录地点">{{ currentLogin.location }}</el-descriptions-item>
          <el-descriptions-item label="登录时间">{{ formatDateTime(currentLogin.loginTime) }}</el-descriptions-item>
          <el-descriptions-item label="退出时间">{{ currentLogin.logoutTime ? formatDateTime(currentLogin.logoutTime) : '未退出' }}</el-descriptions-item>
          <el-descriptions-item label="在线时长">{{ currentLogin.duration ? formatDuration(currentLogin.duration) : '-' }}</el-descriptions-item>
        </el-descriptions>

        <!-- 设备信息 -->
        <div class="mt-4">
          <h4>设备信息</h4>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="User-Agent">{{ currentLogin.userAgent }}</el-descriptions-item>
            <el-descriptions-item label="操作系统">{{ getOSInfo(currentLogin.userAgent) }}</el-descriptions-item>
            <el-descriptions-item label="浏览器">{{ getBrowserInfo(currentLogin.userAgent) }}</el-descriptions-item>
            <el-descriptions-item label="设备类型">{{ getDeviceType(currentLogin.userAgent) }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 登录失败原因 -->
        <div v-if="currentLogin.status === 'failed'" class="mt-4">
          <h4>失败原因</h4>
          <el-alert
            :title="currentLogin.failReason"
            type="error"
            :closable="false"
            show-icon
          />
        </div>

        <!-- 安全提醒 -->
        <div v-if="currentLogin.riskLevel" class="mt-4">
          <h4>安全评估</h4>
          <el-alert
            :title="getRiskLevelText(currentLogin.riskLevel)"
            :type="getRiskLevelType(currentLogin.riskLevel)"
            :closable="false"
            show-icon
          >
            <template #default>
              <div>{{ currentLogin.riskDescription }}</div>
            </template>
          </el-alert>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { ElMessage } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";
import User from "@iconify-icons/ep/user";
import Calendar from "@iconify-icons/ep/calendar";
import Check from "@iconify-icons/ep/check";
import Close from "@iconify-icons/ep/close";
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";
import Download from "@iconify-icons/ep/download";
import View from "@iconify-icons/ep/view";
import dayjs from "dayjs";

defineOptions({
  name: "LogLogin"
});

// 筛选表单
const filterForm = ref({
  username: "",
  status: "",
  loginType: "",
  ip: "",
  dateRange: []
});

// 登录统计
const loginStats = ref({
  total: 8765,
  today: 156,
  success: 8234,
  failed: 531
});

// 登录日志列表
const loginList = ref([]);
const loading = ref(false);

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
});

// 弹窗控制
const detailDialogVisible = ref(false);

// 当前登录记录
const currentLogin = ref(null);

// 获取登录方式标签类型
const getLoginTypeTagType = (type: string) => {
  const typeMap = {
    password: "primary",
    sms: "success",
    wechat: "warning",
    qq: "info"
  };
  return typeMap[type] || "info";
};

// 获取登录方式文本
const getLoginTypeText = (type: string) => {
  const typeMap = {
    password: "账号密码",
    sms: "手机验证码",
    wechat: "微信登录",
    qq: "QQ登录"
  };
  return typeMap[type] || type;
};

// 获取设备信息
const getDeviceInfo = (userAgent: string) => {
  if (!userAgent) return "未知设备";
  
  const os = getOSInfo(userAgent);
  const browser = getBrowserInfo(userAgent);
  
  return `${os} / ${browser}`;
};

// 获取操作系统信息
const getOSInfo = (userAgent: string) => {
  if (!userAgent) return "未知";
  
  if (userAgent.includes("Windows NT 10.0")) return "Windows 10";
  if (userAgent.includes("Windows NT 6.3")) return "Windows 8.1";
  if (userAgent.includes("Windows NT 6.1")) return "Windows 7";
  if (userAgent.includes("Mac OS X")) return "macOS";
  if (userAgent.includes("Linux")) return "Linux";
  if (userAgent.includes("Android")) return "Android";
  if (userAgent.includes("iPhone")) return "iOS";
  
  return "其他";
};

// 获取浏览器信息
const getBrowserInfo = (userAgent: string) => {
  if (!userAgent) return "未知";
  
  if (userAgent.includes("Chrome")) return "Chrome";
  if (userAgent.includes("Firefox")) return "Firefox";
  if (userAgent.includes("Safari")) return "Safari";
  if (userAgent.includes("Edge")) return "Edge";
  if (userAgent.includes("Opera")) return "Opera";
  
  return "其他";
};

// 获取设备类型
const getDeviceType = (userAgent: string) => {
  if (!userAgent) return "未知";
  
  if (userAgent.includes("Mobile") || userAgent.includes("Android") || userAgent.includes("iPhone")) {
    return "移动设备";
  }
  if (userAgent.includes("Tablet") || userAgent.includes("iPad")) {
    return "平板设备";
  }
  
  return "桌面设备";
};

// 获取风险等级文本
const getRiskLevelText = (level: string) => {
  const levelMap = {
    low: "低风险",
    medium: "中风险",
    high: "高风险"
  };
  return levelMap[level] || level;
};

// 获取风险等级类型
const getRiskLevelType = (level: string) => {
  const typeMap = {
    low: "success",
    medium: "warning",
    high: "error"
  };
  return typeMap[level] || "info";
};

// 格式化日期时间
const formatDateTime = (date: string) => {
  return dayjs(date).format("YYYY-MM-DD HH:mm:ss");
};

// 格式化时长
const formatDuration = (minutes: number) => {
  if (minutes < 60) {
    return `${minutes}分钟`;
  }
  
  const hours = Math.floor(minutes / 60);
  const remainingMinutes = minutes % 60;
  
  if (hours < 24) {
    return `${hours}小时${remainingMinutes}分钟`;
  }
  
  const days = Math.floor(hours / 24);
  const remainingHours = hours % 24;
  
  return `${days}天${remainingHours}小时${remainingMinutes}分钟`;
};

// 生成模拟数据
const generateMockData = () => {
  const mockData = [];
  const usernames = ["admin", "operator1", "operator2", "manager1", "manager2", "user1", "user2"];
  const realNames = ["管理员", "操作员1", "操作员2", "经理1", "经理2", "用户1", "用户2"];
  const loginTypes = ["password", "sms", "wechat", "qq"];
  const statuses = ["success", "failed"];
  const ips = ["192.168.1.100", "192.168.1.101", "192.168.1.102", "10.0.0.1", "172.16.0.1", "203.208.60.1", "114.114.114.114"];
  const locations = ["北京市", "上海市", "广州市", "深圳市", "杭州市", "成都市", "武汉市"];
  const userAgents = [
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15",
    "Mozilla/5.0 (iPhone; CPU iPhone OS 14_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1",
    "Mozilla/5.0 (Linux; Android 11; SM-G991B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.120 Mobile Safari/537.36"
  ];
  const riskLevels = ["low", "medium", "high"];
  const failReasons = ["密码错误", "账号不存在", "账号被锁定", "验证码错误", "登录超时"];
  
  for (let i = 1; i <= 80; i++) {
    const username = usernames[Math.floor(Math.random() * usernames.length)];
    const realName = realNames[usernames.indexOf(username)];
    const loginType = loginTypes[Math.floor(Math.random() * loginTypes.length)];
    const status = Math.random() > 0.15 ? "success" : "failed";
    const loginTime = dayjs().subtract(Math.floor(Math.random() * 30), 'day')
      .subtract(Math.floor(Math.random() * 24), 'hour')
      .subtract(Math.floor(Math.random() * 60), 'minute');
    const duration = status === "success" ? Math.floor(Math.random() * 480) + 10 : null;
    const logoutTime = status === "success" && Math.random() > 0.3 ? 
      loginTime.add(duration, 'minute') : null;
    const riskLevel = Math.random() > 0.8 ? riskLevels[Math.floor(Math.random() * riskLevels.length)] : null;
    
    mockData.push({
      id: i,
      username,
      realName,
      loginType,
      status,
      ip: ips[Math.floor(Math.random() * ips.length)],
      location: locations[Math.floor(Math.random() * locations.length)],
      userAgent: userAgents[Math.floor(Math.random() * userAgents.length)],
      loginTime: loginTime.format('YYYY-MM-DD HH:mm:ss'),
      logoutTime: logoutTime ? logoutTime.format('YYYY-MM-DD HH:mm:ss') : null,
      duration,
      riskLevel,
      riskDescription: riskLevel ? `检测到${getRiskLevelText(riskLevel)}登录行为，建议加强安全防护` : null,
      failReason: status === "failed" ? failReasons[Math.floor(Math.random() * failReasons.length)] : null
    });
  }
  
  return mockData.sort((a, b) => dayjs(b.loginTime).valueOf() - dayjs(a.loginTime).valueOf());
};

// 搜索
const handleSearch = () => {
  loadLoginList();
};

// 重置
const handleReset = () => {
  filterForm.value = {
    username: "",
    status: "",
    loginType: "",
    ip: "",
    dateRange: []
  };
  loadLoginList();
};

// 导出
const handleExport = () => {
  ElMessage.success("导出功能开发中...");
};

// 刷新
const handleRefresh = () => {
  loadLoginList();
};

// 查看详情
const handleView = (row: any) => {
  currentLogin.value = row;
  detailDialogVisible.value = true;
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  loadLoginList();
};

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  loadLoginList();
};

// 加载登录日志列表
const loadLoginList = async () => {
  try {
    loading.value = true;
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500));
    
    const mockData = generateMockData();
    loginList.value = mockData.slice(
      (pagination.currentPage - 1) * pagination.pageSize,
      pagination.currentPage * pagination.pageSize
    );
    pagination.total = mockData.length;
  } catch (error) {
    ElMessage.error("加载登录日志失败");
  } finally {
    loading.value = false;
  }
};

// 组件挂载
onMounted(() => {
  loadLoginList();
});
</script>

<style lang="scss" scoped>
.main {
  padding: 20px;
}

.filter-card {
  margin-bottom: 16px;
}

.stat-card {
  margin-bottom: 16px;
  
  .stat-content {
    display: flex;
    align-items: center;
    
    .stat-icon {
      width: 50px;
      height: 50px;
      border-radius: 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 16px;
      font-size: 20px;
      color: white;
      
      &.total-icon {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      }
      
      &.today-icon {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      }
      
      &.success-icon {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      }
      
      &.failed-icon {
        background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
      }
    }
    
    .stat-info {
      flex: 1;
      
      .stat-title {
        font-size: 14px;
        color: #909399;
        margin-bottom: 8px;
      }
      
      .stat-value {
        font-size: 20px;
        font-weight: bold;
        color: #303133;
      }
    }
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.login-detail {
  h4 {
    margin: 20px 0 10px 0;
    color: #303133;
    font-weight: bold;
  }
}

@media (max-width: 768px) {
  .main {
    padding: 10px;
  }
  
  .stat-content {
    flex-direction: column;
    text-align: center;
    
    .stat-icon {
      margin-right: 0;
      margin-bottom: 12px;
    }
  }
  
  .pagination-container {
    text-align: center;
  }
  
  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }
}
</style>